#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <cstring>

int main(int argc, char** argv) {
    int port = 18889;
    if (argc >= 2) {
        port = std::atoi(argv[1]);
    }
    
    int sock = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket");
        return 1;
    }
    
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    
    if (::bind(sock, (sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        close(sock);
        return 1;
    }
    
    std::cout << "Listening on port " << port << " for hand data..." << std::endl;
    
    char buf[65536];
    sockaddr_in src{};
    socklen_t slen = sizeof(src);
    
    while (true) {
        int n = ::recvfrom(sock, buf, sizeof(buf)-1, 0, (sockaddr*)&src, &slen);
        if (n > 0) {
            buf[n] = 0;
            std::cout << "Received " << n << " bytes: " << buf << std::endl;
        }
    }
    
    close(sock);
    return 0;
}
